<template>
	<view class="container">
		<up-sticky bgColor="#fff">
			<view class="search">
				<up-search placeholder="输入设备编号" v-model="sbbhSearchWord" @search="sbbhSearch" @custom="sbbhSearch"
					@clickIcon="scanQRCode" searchIcon="scan" :show-action="false" shape="round" height="36"
					bgColor="#fff" placeholderColor="#999" searchIconColor="#252B93" color="#333"></up-search>
			</view>
			<!-- 日期筛选栏 -->
			<view class="date-filter">
				<view class="date-range">
					<view :class="['date-item', dateRange === 'all' ? 'active' : '']" @tap="switchDateRange('all')">
						全部
					</view>
					<view :class="['date-item', dateRange === 'current' ? 'active' : '']"
						@tap="switchDateRange('current')">
						本月
					</view>
					<view :class="['date-item', dateRange === 'next' ? 'active' : '']" @tap="switchDateRange('next')">
						下月
					</view>
				</view>
				<picker mode="date" :value="selectedMonth" start="2021-01-01" fields="month" @change="datePickerChange">
					<view class="date-picker-text">
						<text>{{ selectedMonth || '选择月份' }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
		</up-sticky>

		<!-- 任务列表 -->
		<view class="task-list">
			<view class="task-item" @tap="onDeviceClick(item)" v-for="(item) in ListData" :key="item.id">
				<view class="task-info">
					<view class="device-name">{{ item.sbmc }}</view>
					<view class="device-code">设备编号：{{ item.sbbh }}</view>
					<view class="location">使用部门：{{ item.createDept }}</view>
					<view class="maintenance-time">润滑时间：{{ item.executionTime }}</view>
					<view class="operator" v-if="item.createPeople !== null">
						<text class="location">润滑人：</text>
						<text>{{ item.feedbackBy }}</text>
					</view>
				</view>

				<!-- 状态文字 -->
				<view :class="statusStyle(item)">
					<view>{{ getStatusText(item) }}</view>
				</view>
			</view>
		</view>

		<!-- 空状态展示 -->
		<view class="empty-state" v-if="ListData.length === 0">
			<image class="empty-icon" src="/static/images/icon.png" mode="aspectFit"></image>
			<text class="empty-text">暂无润滑任务</text>
		</view>
	</view>
</template>

<script>
	import dayjs from "dayjs/esm/index";

	export default {
		data() {
			return {
				sbbhSearchWord: '', //搜索词
				selectedMonth: '', // 选择的月份，格式：YYYY-MM
				dateRange: 'current', // 日期范围：current/next/quarter
				userBmmc: "",
				userCKCQ: "",
				beginYear: '',
				beginMonth: '',
				endYear: '',
				endMonth: '',
				pageIndex: 1, //分页信息
				pageSize: 10,
				total: 0,
				ListData: [],
				ListDataTemp: []
			};
		},
		onLoad() {
			this.userBmmc = uni.getStorageSync('user_permission').BM;
			var ckcq = uni.getStorageSync('user_permission').CHANGQU;
			if (ckcq === '全部') {
				this.userCKCQ = '';
			} else {
				this.userCKCQ = ckcq;
			}

			// 初始化列表
			this.filterByDate();
			this.getData();

			uni.$on('updateListData', (data) => {
				//一键确认成功后隐藏一键确认按钮
				this.ListData.forEach(item => {
					if (item.id === data.planId) {
						item.unitSignature = data.unitSignature;
						item.eqptOprSignature = data.eqptOprSignature;
					}
				})
			})
		},
		// 触底刷新
		onReachBottom() {
			this.loadNextPage();
		},
		methods: {
			//旧/设备编号搜索
			sbbhSearch() {
				this.resetPageInfo();
				this.getData();
			},

			//扫码搜索
			scanQRCode() {
				uni.scanCode({
					success: (res) => {
						this.sbbhSearchWord = res.result;
						this.sbbhSearch();
					},
					fail: (err) => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},

			// 选择框切换 日期范围
			switchDateRange(range) {
				this.dateRange = range;
				this.selectedMonth = ''; // 清除选择的月份
				this.resetPageInfo();
				this.filterByDate();
				this.getData();
			},

			//日期选择变化
			datePickerChange(item) {
				this.selectedMonth = item.detail.value;
				//清空选择内容
				this.dateRange = '';
				this.resetPageInfo();
				this.filterByDate();
				this.getData();
			},

			// 处理选择的日期范围，并根据日期调用接口筛选数据
			filterByDate() {
				if (this.dateRange === '' && this.selectedMonth === '') {
					this.prepareInbounds(['', '']); //空就是查询全部
				}
				//如果是日期选择的年月
				if (this.dateRange === '' && this.selectedMonth !== '') {
					let yearMonth = dayjs(this.selectedMonth).format('YYYY-M').split('-');
					this.prepareInbounds(yearMonth);
				}
				//如果是单选按钮的
				if (this.dateRange !== '') {
					// 使用日期范围
					switch (this.dateRange) {
						case 'current':
							let currentMonth = dayjs().format("YYYY-M").split('-');
							this.prepareInbounds(currentMonth);
							break;
						case 'next':
							let nextMonth = dayjs().add(1, 'month').format("YYYY-M").split('-');
							this.prepareInbounds(nextMonth);
							break;
						case 'quarter':
							let begin = dayjs().startOf('quarter').format('YYYY-M').split('-');
							let end = dayjs().endOf('quarter').format('YYYY-M').split('-');
							this.beginYear = begin[0];
							this.beginMonth = begin[1];
							this.endYear = end[0];
							this.endMonth = end[1];
							break;
						case 'all':
							this.prepareInbounds(['', '']); //空就是查询全部
							break;
					}
				}
			},

			//准备入参年月
			prepareInbounds(yearMonth) {
				this.beginYear = yearMonth[0];
				this.beginMonth = yearMonth[1];
				this.endYear = yearMonth[0];
				this.endMonth = yearMonth[1];
			},

			// 查询当前部门指定时间段内的润滑计划
			async getData() {
				try {
					// const res = await this.$commonUnits.postRequest(
					// 	"sbby.maintenancemobilebiz.getMaintenanceSbListByPage.mobile", {
					// 		maintenanceLevel: '1',
					// 		bmmc: this.userBmmc,
					// 		whichworhshop: this.userCKCQ,
					// 		searchWord: this.sbbhSearchWord,
					// 		beginYear: this.beginYear,
					// 		beginMonth: this.beginMonth,
					// 		endYear: this.endYear,
					// 		endMonth: this.endMonth,
					// 		pageIndex: this.pageIndex,
					// 		pageSize: this.pageSize,
					// 	}
					// );

					// if (res.code === '1') {
					// 	this.ListDataTemp = res.res.list;
					// 	this.total = res.res.total;
					// 	// 分页处理逻辑
					// 	if (this.pageIndex === 1) {
					// 		this.ListData = [...this.ListDataTemp];
					// 	} else {
					// 		this.ListData = [...this.ListData, ...this.ListDataTemp];
					// 	}
					// }
					this.ListData = [{
							"sbbh": "0520010426100852",
							"sbmc": "流动车式干油泵",
							"id": "d64679a5402a4da0982b460981fd1df7",
							"lubricationStandardId": "A1B2C3D4E5F67890",
							"executionTime": "2023-06-1509:00:00",
							"feedbackRecord": "按照标准完成润滑，设备运行正常",
							"equipmentId": "d64679a5402a4da0982b460981fd1df7",
							"executionStatus": 0,
							"createPeopleId": "USER001",
							"createTime": "2023-06-10 14:30:00",
							"createPeople": "张三",
							"createDept": "船坞总装一部",
							"createDeptId": "DEPT001",
							"updateTime": "2023-06-15 10:15:00",
							"updatePeople": "张三"
						},
						{
							"sbbh": "052001020106000785",
							"sbmc": "门座式起重机",
							"id": "5E7A3C1F6E9B0D2A4C6E8F1B38F2B4D",
							"lubricationStandardId": "B2C3D4E5F67890A1",
							"executionTime": "2023-06-20T14:00:00",
							"feedbackRecord": "润滑过程中发现少量泄漏，已处理",
							"equipmentId": "4028b88177f652ce0177f7252cd2274a",
							"executionStatus": 1,
							"createPeopleId": "USER002",
							"createTime": "2023-06-12 10:15:00",
							"createPeople": "李四",
							"createDept": "设备维护部",
							"createDeptId": "DEPT001",
							"updateTime": "2023-06-20 15:30:00",
							"updatePeople": "李四"
						},
						{
							"sbbh": "866798798715696",
							"sbmc": "吊式起重机",
							"id": "3C1F6E9B0D2A4C6E8F1B38F2B4D5E7A",
							"lubricationStandardId": "C3D4E5F67890A1B2",
							"executionTime": "2023-06-25 11:00:00",
							"feedbackRecord": null,
							"equipmentId": "EQ456789123",
							"executionStatus": 0,
							"createPeopleId": "USER001",
							"createTime": "2023-06-18 16:45:00",
							"createPeople": "张三",
							"createDept": "设备维护部",
							"createDeptId": "DEPT001",
							"updateTime": null,
							"updatePeople": null
						},
						{
							"id": "6E9B0D2A4C6E8F1B38F2B4D5E7A3C1F",
							"lubricationStandardId": "D4E5F67890A1B2C3",
							"executionTime": "2023-06-28T10:00:00",
							"feedbackRecord": "设备停机，润滑计划取消",
							"equipmentId": "EQ654321987",
							"executionStatus": 2,
							"createPeopleId": "USER003",
							"createTime": "2023-06-20 09:30:00",
							"createPeople": "王五",
							"createDept": "设备维护部",
							"createDeptId": "DEPT001",
							"updateTime": "2023-06-27 16:20:00",
							"updatePeople": "王五"
						},
					]
					this.total = 4
				} catch (error) {
					console.error('请求失败:', error);
					throw error; // 抛出错误供上层捕获
				}
			},

			async loadNextPage() {
				//超出总条数不加载
				if (this.ListData.length >= this.total) return;
				this.pageIndex++;
				try {
					await this.getData();
				} catch (error) {
					this.pageIndex--; // 回滚页码
					console.error('加载更多列表数据失败:', error);
				}
			},

			//重置页码信息
			resetPageInfo() {
				this.pageIndex = 1;
				this.pageSize = 10;
				this.total = 0;
			},

			// 状态文本样式
			statusStyle(item) {
				switch (item.executionStatus) {
					case 0: // 未执行
						return 'task-status pending';
					case 1: // 已执行
						return 'task-status completed';
					case 2: // 已取消
						return 'task-status cancelled';
					default:
						return 'task-status pending';
				}
			},

			// 获取状态文本
			getStatusText(item) {
				switch (item.executionStatus) {
					case 0: // 未执行
						return '待润滑';
					case 1: // 已执行
						return '已润滑';
					case 2: // 已取消
						return '已取消';
					default:
						return '待润滑';
				}
			},

			// 点击跳转设备详情页
			onDeviceClick(item) {
				uni.navigateTo({
					url: `/pageTwo/pages/lubrication/detail?id=${item.id}&equipmentId=${item.equipmentId}&date=${item.executionTime}`
				});
			},
		}
	};
</script>

<style scoped lang="scss">
	/* 保持原有样式不变 */
	.container {
		min-height: 100vh;
		background: #f5f7fa;
	}

	/* 润滑人信息样式 */
	.operator {
		font-size: 26rpx;
		color: #666;
		margin-top: 8rpx;
	}

	.operator .label {
		color: #999;
	}

	/* 任务列表样式 */
	.task-list {
		padding: 20rpx;
	}

	.task-item {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.device-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 12rpx;
	}

	.device-code,
	.location,
	.maintenance-time {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.task-status {
		padding: 8rpx 24rpx;
		border-radius: 24rpx;
		font-size: 26rpx;
	}

	.task-status.pending {
		background: #fff7e6;
		color: #fa8c16;
	}

	.task-status.cancelled {
		background: #fff1f0;
		color: #ff4d4f;
	}

	.task-status.completed {
		background: #f6ffed;
		color: #52c41a;
	}

	/* 空状态样式 */
	.empty-state {
		padding: 120rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	/* 日期筛选样式 */
	.date-filter {
		background: #ffffff;
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.date-range {
		display: flex;
		gap: 20rpx;
	}

	.date-item {
		font-size: 26rpx;
		color: #666;
		padding: 8rpx 24rpx;
		border-radius: 24rpx;
		background: #f5f7fa;
	}

	.date-item.active {
		background: #e6f7ff;
		color: #1890ff;
	}

	.date-picker-text {
		display: flex;
		align-items: center;
		font-size: 26rpx;
		color: #666;
		padding: 8rpx 0;
	}

	.picker-arrow {
		margin-left: 8rpx;
		transform: rotate(90deg);
		color: #999;
	}

	.search {
		padding-top: 10px;
		background-color: #fff;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(2rpx);
		}

		:deep(.u-search__content) {
			border-radius: 50rpx !important;
			border: 2rpx solid #1890ff !important;
			box-shadow: 0 2rpx 8rpx rgba(37, 43, 147, 0.1);
			border: 1rpx solid #eee;

			&:focus-within {
				border-color: #1890ff !important;
				box-shadow: 0 2rpx 12rpx rgba(37, 43, 147, 0.2);
			}
		}

		:deep(.u-search__content__input) {
			font-size: 14px;
			padding-left: 20rpx;
		}

		:deep(.u-icon__icon) {
			font-size: 18px !important;
		}
	}
</style>